#!/usr/bin/python
# -*- coding:utf-8 -*-
# -------------------------------------------------------
# @author  : 龍皓
# @time    : 2025/1/5 14:47
# @function: 应用主窗口
# @version : 1.0.0
# -------------------------------------------------------

import os
import threading
import time
import tkinter as tk
from tkinter import filedialog, messagebox, ttk

from script.DouyinUtil import DouyinUtil

class MainWindow(tk.Tk):
    def __init__(self):
        super().__init__()
        self.stop_flag = False
        self.title('媒体助手')
        self.geometry('800x600')
        self.du = DouyinUtil()
        # 初始化界面元素
        self.create_widgets()
        # 设置行列权重以支持自适应
        self.configure_grid()

    def create_widgets(self):
        self.media_folder_label = tk.Label(self, text="选择要处理的文件夹")
        self.media_folder_label.grid(row=0, column=0, padx=10, pady=10, sticky=tk.W)

        self.media_folder_path = tk.StringVar()
        self.media_folder_entry = tk.Entry(self, textvariable=self.media_folder_path, width=75)
        self.media_folder_entry.grid(row=0, column=1, padx=10, pady=10, sticky=tk.W)

        self.media_folder_button = tk.Button(self, text="浏览", command=self.select_media_folder)
        self.media_folder_button.grid(row=0, column=2, padx=10, pady=10, sticky=tk.E)

        # 输出文件夹选择
        self.output_folder_label = tk.Label(self, text="选择输出文件夹:")
        self.output_folder_label.grid(row=1, column=0, padx=10, pady=10, sticky=tk.W)

        self.output_folder_path = tk.StringVar()
        self.output_folder_entry = tk.Entry(self, textvariable=self.output_folder_path, width=75)
        self.output_folder_entry.grid(row=1, column=1, padx=10, pady=10, sticky=tk.W)

        self.output_folder_button = tk.Button(self, text="浏览", command=self.select_output_folder)
        self.output_folder_button.grid(row=1, column=2, padx=10, pady=10, sticky=tk.E)

        # 开始按钮
        self.start_button = tk.Button(self, text="开始处理", command=self.start_processing)
        self.start_button.grid(row=2, column=0, columnspan=3, pady=20, sticky=tk.N)

        # 停止按钮
        self.stop_button = tk.Button(self, text="停止处理", command=self.stop_processing)
        self.stop_button.grid(row=2, column=1, columnspan=3, pady=20, sticky=tk.N)

        # 进度条
        self.progress_bar = ttk.Progressbar(self, length=400, mode='determinate')
        self.progress_bar.grid(row=3, column=0, columnspan=3, padx=10, pady=20, sticky=tk.EW)

        # 日志框
        self.log_label = tk.Label(self, text="终端日志:")
        self.log_label.grid(row=4, column=0, padx=10, pady=10, sticky=tk.W)

        self.log_text = tk.Text(self, height=10, width=70)
        self.log_text.grid(row=5, column=0, columnspan=3, padx=10, pady=10, sticky=tk.NSEW)

        # 禁用文本框（只读）
        self.log_text.config(state=tk.DISABLED)

    def configure_grid(self):
        # 设置列权重
        self.grid_columnconfigure(0, weight=1)  # 第一列权重
        self.grid_columnconfigure(1, weight=1)  # 第二列权重
        self.grid_columnconfigure(2, weight=2)  # 第三列权重，稍宽

        # 设置行权重
        self.grid_rowconfigure(5, weight=1)  # 日志框所在行拉伸

    def select_media_folder(self):
        folder_selected = filedialog.askdirectory(title="选择媒体文件夹")
        if folder_selected:
            self.media_folder_path.set(folder_selected)

    def select_output_folder(self):
        folder_selected = filedialog.askdirectory(title="选择输出文件夹")
        if folder_selected:
            self.output_folder_path.set(folder_selected)

    def start_processing(self):
        media_folder = self.media_folder_path.get()
        output_folder = self.output_folder_path.get()

        if not media_folder or not output_folder:
            messagebox.showerror("错误", "请先选择媒体文件夹和输出文件夹。")
            return

        # 重置停止标志
        self.stop_flag = False

        # 禁用界面控件，防止重复点击
        self.start_button.config(state=tk.DISABLED)
        self.media_folder_button.config(state=tk.DISABLED)
        self.output_folder_button.config(state=tk.DISABLED)

        # 清空日志框
        self.log_text.config(state=tk.NORMAL)
        self.log_text.delete(1.0, tk.END)
        self.log_text.config(state=tk.DISABLED)

        # 启动后台线程处理视频
        self.thread = threading.Thread(target=self.process_videos, args=(media_folder, output_folder))
        self.thread.start()

    def stop_processing(self):
        self.stop_flag = True
        self.update_log("正在等待任务完成当前视频处理后停止...")

    def process_videos(self, media_folder, output_folder):
        # 获取文件夹中的所有视频文件
        video_files = self.du.get_video_files(media_folder)
        total_videos = len(video_files)

        if total_videos == 0:
            self.update_log("没有找到视频文件。")
            return

        # 设置进度条最大值
        self.progress_bar['maximum'] = total_videos

        for idx, video_file in enumerate(video_files, 1):
            if self.stop_flag:  # 检查是否停止处理
                self.update_log("检测到停止信号，结束任务。")
                break

            # 更新进度条
            self.progress_bar['value'] = idx
            self.update_log(f"正在处理: {video_file}")

            # 提取视频最后一帧并识别文字
            last_frame = self.du.extract_last_frame(video_file, output_folder)
            if last_frame:
                recognized_text = self.du.ocr_recognize_text(last_frame)
                self.update_log(f"识别出的文字: {recognized_text}")

                # 根据识别的文字创建文件夹并保存视频
                folder = self.du.create_folder_and_save(output_folder, video_file, recognized_text, last_frame)

            # 更新进度条
            self.progress_bar.update()

            # 模拟处理时间
            time.sleep(1)

        # 处理完成后启用控件
        self.update_log("处理完成或任务被停止!")
        self.enable_controls()

        # 弹出提示框
        messagebox.showinfo("处理结果", "所有文件已处理完成或已停止处理！")  # 弹窗提示


    def update_log(self, message):
        # 更新日志框中的内容
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.yview(tk.END)  # 自动滚动到底部
        self.log_text.config(state=tk.DISABLED)

    def enable_controls(self):
        self.start_button.config(state=tk.NORMAL)
        self.media_folder_button.config(state=tk.NORMAL)
        self.output_folder_button.config(state=tk.NORMAL)